import { ref, watch, computed, nextTick } from "vue";

export default function useFixed(props) {
  const TITLE_HEIGHT = 30;
  const groupRef = ref(null); //绑定ul
  const listHeights = ref([]); //存储高度的数组
  const scrollY = ref(0); //滚动Y轴的距离
  const currentIndex = ref(0); //属于哪个区间的索引
  const distance = ref(0);
  /* 
  第五步:依赖数据,数据渲染之后才调用,使用nextTick进行处理
  @return 当前处在的title值
  */
  const fixedTitle = computed(() => {
    if (scrollY.value < 0) {
      return "";
    }
    const currentGroup = props.data[currentIndex.value];
    return currentGroup ? currentGroup.title : "";
  });

  /* 
  第六步:标签相互贴近时,上移
  @return 当前处在的title值
  */
  const fixedStyle = computed(() => {
    const distanceVal = distance.value;
    const diff =
      distanceVal > 0 && distanceVal < TITLE_HEIGHT
        ? distanceVal - TITLE_HEIGHT
        : 0;
    return {
      transform: `translate3d(0,${diff}px,0)`,
    };
  });
  /* 
  第二步:依赖数据,数据渲染之后才调用,使用nextTick进行处理
  */
  watch(
    () => props.data,
    async () => {
      await nextTick();
      calculate();
    }
  );
  /* 
  第四步:依赖scrollY的变换,获得新的Y坐标,通过对比数组中的值来获得索引
  */
  watch(scrollY, (newY) => {
    const listHeightsVal = listHeights.value; //赋值一下
    for (let i = 0; i < listHeightsVal.length - 1; i++) {
      const heightTop = listHeightsVal[i];
      const heightBottom = listHeightsVal[i + 1];
      if (newY >= heightTop && newY <= heightBottom) {
        currentIndex.value = i;
        distance.value = heightBottom - newY; //判断下一个li与当前Y的距离
      }
    }
  });

  /* 
  第一步:
   计算并将ul中每个li距离顶部的高度依次存入数组
   @return undefiend
  */
  function calculate() {
    //获取所有的孩子节点
    const list = groupRef.value.children;
    //依次将高度存入数组
    const listHeightsVal = listHeights.value;
    let height = 0;
    listHeightsVal.length = 0;
    listHeightsVal.push(height);
    for (let i = 0; i < list.length; i++) {
      height += list[i].clientHeight;
      listHeightsVal.push(height);
    }
  }
  /* 
  第三步:获得滚动的Y轴坐标
   @return undefiend
  */
  function onScroll(pos) {
    scrollY.value = -pos.y;
  }
  return {
    groupRef,
    onScroll,
    fixedTitle,
    fixedStyle,
    currentIndex,
  };
}
